<!--
 * @Description: 商品详情页面组件
 * @Author: hai-27
 * @Date: 2020-02-16 20:20:26
 * @LastEditors: hai-27
 * @LastEditTime: 2020-03-07 21:59:26
 -->
<template>
  <div id="details">
    <!-- 头部 -->
    <div class="page-header">
      <div class="title">
        <span>{{ pojo[0].name }}</span>
        <router-link style="float:right" v-if="pojo[0].activity.name!==null&&pojo[0].activity.name!==undefined&&pojo[0].activity.name!==''" :to="{path: '/goods', query: {aid:pojo[0].activity.aid}  }">
          <span >{{ pojo[0].activity.name }}</span>
        </router-link>
      </div>
    </div>
    <!-- 头部END -->

    <!-- 主要内容 -->
    <div class="main">
      <!-- 左侧商品轮播图 -->
      <div class="block">
        <el-carousel height="560px">
          <el-carousel-item v-for="item in pojo" :key="item.gid">
            <el-image style="height:560px;" :src="baseURL+'data/picture/'+item.picture.url"
                      :preview-src-list="[baseURL+'data/picture/'+item.picture.url]"
                      fit='cover'/>
          </el-carousel-item>
        </el-carousel>
      </div>
      <!-- 左侧商品轮播图END -->

      <!-- 右侧内容区 -->
      <div class="content">
        <h1 class="name">{{ pojo[0].name }}</h1>
        <router-link :to="{path:'/merchant', query: {mid:pojo[0].merchant.mid} }">
          <p class="store">{{ pojo[0].merchant.name }}</p>
        </router-link>
        <div class="price">
          <span>{{ pojo[0].price }}元</span>
        </div>
        <div class="pro-list">
          <el-radio-group v-model="salegoods" v-for="item in pojo[0].list" :key="item.sgid">
            <el-radio class="intro" :label="item" border>{{ item.number }} ({{ item.unit }})
            </el-radio>
            <span width="20px"/>
          </el-radio-group>
          <br>
          <span class="pro-name">选择购买数量[0,{{ pojo[0].number }}]</span>
          <el-input-number class="pro-price" v-model="number" :min="0" :max="pojo[0].number"></el-input-number>
          <br>
          <br>
          <span class="pro-name">单价</span>
          <span class="pro-price">
            <span>{{ salegoods.price }}元</span>
          </span>
          <p class="price-sum">总计 : {{ sumPrice }}元</p>
        </div>
        <!-- 内容区底部按钮 -->
        <div class="button">
          <span style="float:left">销量:{{pojo[0].sale}}</span>
          <span style="float:right">浏览量:{{pojo[0].view}}</span>
          <br>
          <el-button class="shop-cart" :disabled="dis" @click="addShoppingCart">加入购物车</el-button>
          <el-button class="like" @click="addCollect(gid)">喜欢</el-button>
        </div>
        <!-- 内容区底部按钮END -->
        <div class="pro-policy">
          <ul>
            <li>
              <i class="el-icon-circle-check"
                 v-if="helper.isNull(pojo[0].merchant)||helper.isNull(pojo[0].merchant.name)">官方自营</i>
              <i class="el-icon-circle-check"
                 v-if="!helper.isNull(pojo[0].merchant)&&!helper.isNull(pojo[0].merchant.name)">{{
                  pojo[0].merchant.name
                }}旗舰店</i>
            </li>
            <li>
              <i class="el-icon-circle-check"
                 v-if="helper.isNull(pojo[0].merchant)||helper.isNull(pojo[0].merchant.name)">官方发货</i>
              <i class="el-icon-circle-check"
                 v-if="!helper.isNull(pojo[0].merchant)&&!helper.isNull(pojo[0].merchant.name)">{{
                  pojo[0].merchant.name
                }}旗舰店发货</i>
            </li>
            <li>
              <i class="el-icon-circle-check"></i> 7天无理由退货
            </li>
            <li>
              <i class="el-icon-circle-check"></i> 7天价格保护
            </li>
          </ul>
        </div>
      </div>
      <!-- 右侧内容区END -->
    </div>
    <!-- 主要内容END -->
    <center>
      <div style="width:1200px">
        <br>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="概述-参数" name="first">
            <p v-html="pojo[0].describe.content"></p>
          </el-tab-pane>
          <el-tab-pane label="用户评价" name="second">
            <MallComment
                :commentList="this.commentsList"
                :commentNum="this.commentsList.length"
                @doSend="replyComment"
                @doChidSend="replyCommentReply"
            >
            </MallComment>
          </el-tab-pane>
        </el-tabs>
      </div>
    </center>
  </div>
</template>
<script>
import {mapActions} from "vuex";
import MallComment from 'bright-comment';

export default {
  components: {
    MallComment
  },
  data() {
    return {
      /**
       * @评论内容
       * */
      commentsList: [],
      /**
       * @标签页-商品详情-评论
       * */
      activeName: 'second',
      /**
       * @商品
       * */
      pojo: [this.$store.state.Pojo.GoodsVo],
      /**
       * @商品主键
       * */
      gid: "",
      /**
       * @商品选定套餐
       * */
      salegoods: "",
      /**
       * @商品数量
       * */
      number: 0,
      /**
       * @静态数据
       * */
      dis: false, // 控制“加入购物车按钮是否可用”
      productID: "", // 商品id
      productDetails: "", // 商品详细信息
      productPicture: "" // 商品图片
    };
  },
  // 通过路由获取商品id
  activated() {
    if (!this.helper.isNull(this.$route.query.gid)) {
      this.gid = this.$route.query.gid;
    }
  },
  computed: {
    /**
     * @总价
     * */
    sumPrice() {
      return this.number * this.salegoods.price;
    },
    /**
     * @后端资源路由
     * */
    baseURL() {
      return this.$store.state.baseURL;
    },
    /**
     * @通用函数
     * */
    helper() {
      return this.$helper;
    },
    /**
     * @全局变量
     * */
    state() {
      return this.$store.state;
    }
  },
  watch: {
    // 监听商品id的变化，请求后端获取商品数据
    gid: function (val) {
      this.getDetails(val);
      this.loadComments(val);
      this.saveHistory(this.$store.getters.getUser.cid, this.gid);
      //this.getDetailsPicture(val);
    }
  },
  created() {
    /*if (!this.helper.isNull(this.$route.query.gid)) {
      this.getDetails(this.$route.query.gid);
    }*/
  },
  methods: {
    ...mapActions(["unshiftShoppingCart", "addShoppingCartNum"]),
    /**
     * @回复回复
     * */
    replyCommentReply(content,bid,pid){
      console.log(content,bid, pid);
      let tobject=null,to='';
      if(bid.toString().substring(0,3)==="300"){
        tobject={cid:bid};
        to=1;
      }else if(bid.toString().substring(0,3)==="500"){
        tobject={mid:bid};
        to=2;
      }
      let _this = this;
      this.axios.post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Reply + '/'+this.$store.state.mappings.save+'?'+ 'from=' + 1 + '&to=' + to+ '&OperatorId=' + this.$store.getters.getUser.cid,
          {
            reid: "",
            coid: pid.split("200")[1],
            from: {cid:this.$store.getters.getUser.cid},
            to: tobject,
            context: content,
            like: 0,
            state: 1
          })
          .then(res => {
            console.log(res.data)
            _this.loadComments();
          })
    },
    /**
     * @回复评论
     * */
    replyComment(val){
      //console.log(val);
      let _this = this;
      this.$axios.post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Comments + '/'+this.$store.state.mappings.save+'?'+ 'i=' + 1 + '&OperatorId=' + this.$store.getters.getUser.cid,
          {
            coid: "",
            user: {cid:this.$store.getters.getUser.cid},
            good: {gid:this.gid},
            context: val,
            like: 0,
            state: 1,
            creattime:'',
            l:[]
          })
          .then(res => {
            //console.log(res.data)
            _this.loadComments();
          })

    },
    /**
     * @浏览量增加
     * */
    upView(val) {
      console.log(val);
      this.axios.post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Goods + '/' + this.$store.state.mappings.save + '?' + 'OperatorId=' + this.$store.getters.getUser.cid,
          {
            "gid": val.gid,
            "name": val.name,
            "price": val.price,
            "merchant": val.merchant,
            "card": val.card,
            "picture": val.picture,
            "describe": val.describe,
            "number": val.number,
            "activity": val.activity,
            "creattime": "",
            "state": val.state,
            "view": val.view + 1,
            "sale": val.sale,
            "list": val.list
          })
          .then(res => {
            console.log(res.data)
          }).catch(err => {
        console.log(err)
      })
    },
    /**
     * @保存历史足迹
     * */
    saveHistory(cid, gid) {
      //console.log(cid,gid);
      //console.log(val)
      let _this = this;
      this.axios.post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.History + '/' + this.$store.state.mappings.save + '?' + 'OperatorId=' + cid,
          {
            hid: -1,
            customer: {cid: cid},
            good: {gid: gid}
          })
          .then(res => {
            //console.log(res.data)
          })
    },
    /**
     * @回复类型装换
     * */
    getReplyList(val, root) {
      let ans = [];
      for (let i = 0; i < val.length; i++) {
        let obj = val[i];
        let temp = {
          id: "400" + obj.reid,
          commentUser: this.getUser(obj.from),
          targetUser: this.getUser(obj.to, root.user),
          content: obj.context,
          createDate: obj.creattime,
          childrenList: []
        };
        ans.push(temp);
      }
      return ans;
    },
    /**
     * @评论类型装换
     * */
    getComments(obj) {
      return {
        id: "200" + obj.coid,
        commentUser: this.getUser(obj.user),
        targetUser: this.getUser(),
        content: obj.context,
        createDate: obj.creattime,
        childrenList: this.getReplyList(obj.l, obj)
      };
    },
    /**
     * @评论用户类型装换
     * */
    getUser(obj, temp) {
      if (this.helper.isNull(obj)) {
        if (!this.helper.isNull(temp)) {
          if (temp.cid === undefined || temp.cid === null || temp.cid === '') {
            //商家
            return {
              id: temp.mid,
              nickName: temp.name,
              avatar: this.baseURL + 'data/picture/' + temp.pic.url
            };
          } else {
            //顾客
            return {
              id: temp.cid,
              nickName: temp.name,
              avatar: this.baseURL + 'data/picture/' + temp.pic.url
            };
          }
        }
        return {
          id: "",
          nickName: "",
          avatar: ""
        };
      }
      if (obj.cid === undefined || obj.cid === null || obj.cid === '') {
        //商家
        return {
          id: obj.mid,
          nickName: obj.name,
          avatar: this.baseURL + 'data/picture/' + obj.pic.url
        };
      } else {
        //顾客
        return {
          id: obj.cid,
          nickName: obj.name,
          avatar: this.baseURL + 'data/picture/' + obj.pic.url
        };
      }
    }
    ,
    /**
     * @导入评论
     * */
    loadComments(val) {
      let _this = this;
      this.$axios.get(this.$store.state.baseURL + 'client/' + this.state.controller.Comments + '/queryLike?' + 'OperatorId=1'
          + '&gid=' + this.gid)
          .then(res => {
            let ans = [];
            for (let i = 0; i < res.data.length; i++) {
              ans.push(this.getComments(res.data[i]));
            }
            _this.commentsList = ans;
            //console.log(_this.commentsList);
          })
    }
    ,
    /**
     * @切换标签页
     * */
    handleClick(tab, event) {
      //console.log(tab, event);
    }
    ,
    // 获取商品详细信息
    getDetails(gid) {
      let _this = this;
      this.$axios.post(this.$store.state.baseURL + 'client/' + this.state.controller.Goods + '/query?' + 'OperatorId=1',
          {
            "page": 1,
            "pageSize": 10,
            "sortType": 0,
            "sortBy": 10,
            "gid": gid,
            "state": 1,
          })
          .then(res => {
            _this.pojo = res.data.goodsVoList;
            this.upView(this.pojo[0]);
            //console.log(_this.pojo);
          })
    }
    ,
    // 获取商品图片
    getDetailsPicture(val) {
      this.$axios
          .post("/api/product/getDetailsPicture", {
            productID: val
          })
          .then(res => {
            this.productPicture = res.data.ProductPicture;
          })
          .catch(err => {
            return Promise.reject(err);
          });
    }
    ,
    /**
     * @把good转变成购物车内的商品
     * */
    getShoppingCartItem(goods, salegoods, number) {
      return {
        id: "", // 购物车id
        gid: goods.gid, // 商品id
        name: goods.name, // 商品名称
        img: goods.picture.url, // 商品图片
        num: number, // 商品数量
        maxNum: goods.number, // 商品限购数量
        check: false, // 是否勾选
        sgid: salegoods.sgid,//套餐id
        price: salegoods.price, // 套餐价格
        unit: salegoods.unit,//套餐单位
        sgid_number: salegoods.number,//套餐数量

      };
    },
    // 加入购物车
    addShoppingCart() {
      /*console.log("购买了" + '<' + this.gid + '>' + this.pojo[0].name + ":" + "<"
          + this.salegoods.sgid + ">" + this.salegoods.price + '/'
          + this.salegoods.number + this.salegoods.unit + "=一共"
          + this.number + this.salegoods.unit + "=>=总计=>" + this.sumPrice + "元");*/
      // 判断是否登录,没有登录则显示登录组件
      if (!this.$store.getters.getUser) {
        this.$store.dispatch("setShowLogin", true);
        return;
      }
      if (this.helper.isNull(this.salegoods)) {
        this.notifyError("请选择套餐");
        return;
      }
      if (this.number === 0) {
        this.notifyError("请选择数量");
        return;
      }

      let val = this.getShoppingCartItem(this.pojo[0], this.salegoods, this.number);
      let shoppingCartList = this.$store.getters.getShoppingCart;
      for (let i = 0; i < shoppingCartList.length; i++) {
        if (shoppingCartList[i].sgid === val.sgid) {
          if (shoppingCartList[i].num < shoppingCartList[i].maxNum) {
            //该商品在购物车里面已经有了,增加数量
            this.addShoppingCartNum({sgid: val.sgid, number: val.num})
            let cart = JSON.stringify(this.$store.getters.getShoppingCart);
            localStorage.setItem("shoppingCart", cart);
            this.notifySucceed("成功增加" + val.name + "(" + val.price + "元/"
                + val.sgid_number + "" + val.unit + ")" + "的数量");
            //console.log(shoppingCartList)
            return;
          } else {
            //达到了最大数量上限,不可添加
            this.dis = true;
            this.notifyError("商品" + val.name + "(" + val.price + "元/"
                + val.sgid_number + "" + val.unit + ")" + "的数量已经达到最大上限,已不可添加");
            //console.log(shoppingCartList)
            return;
          }
        }
      }
      // 新加入购物车成功
      this.unshiftShoppingCart(val);
      let cart = JSON.stringify(this.$store.getters.getShoppingCart);
      localStorage.setItem("shoppingCart", cart);
      this.notifySucceed("成功添加" + this.pojo[0].name + "到购物车");
      //console.log(shoppingCartList)
    }
    ,
    addCollect(gid) {
      // 判断是否登录,没有登录则显示登录组件
      if (!this.$store.getters.getUser) {
        this.$store.dispatch("setShowLogin", true);
        return;
      }
      this.$axios
          .post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Collect +
              '/' + this.$store.state.mappings.save + '?' + 'OperatorId=' + this.$store.getters.getUser.cid,
              {
                coid: -1,
                customer: {cid: this.$store.getters.getUser.cid},
                good: {gid: gid},
                state: 1
              })
          .then(res => {
            switch (res.data) {
              case 0:
                // 提示删除失败信息
                this.notifyError("失败==>SQL调用失败");
                break;
              case -1:
                // 提示删除失败信息
                this.notifyError("失败==>服务熔断");
                break;
              default:
                // 收藏成功
                // 提示成功信息
                this.notifySucceed("成功==>收藏到收藏夹");
                break;
            }
          })
          .catch(err => {
            return Promise.reject(err);
          });
    }
  }
};
</script>
<style>
/* 头部CSS */
#details .page-header {
  height: 64px;
  margin-top: -20px;
  z-index: 4;
  background: #fff;
  border-bottom: 1px solid #e0e0e0;
  -webkit-box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.07);
  box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.07);
}

#details .page-header .title {
  width: 1225px;
  height: 64px;
  line-height: 64px;
  font-size: 18px;
  font-weight: 400;
  color: #212121;
  margin: 0 auto;
}

#details .page-header .title p {
  float: left;
}

#details .page-header .title .list {
  height: 64px;
  float: right;
}

#details .page-header .title .list li {
  float: left;
  margin-left: 20px;
}

#details .page-header .title .list li a {
  font-size: 14px;
  color: #616161;
}

#details .page-header .title .list li a:hover {
  font-size: 14px;
  color: #ff6700;
}

/* 头部CSS END */

/* 主要内容CSS */
#details .main {
  width: 1225px;
  height: 560px;
  padding-top: 30px;
  margin: 0 auto;
}

#details .main .block {
  float: left;
  width: 560px;
  height: 560px;
}

#details .el-carousel .el-carousel__indicator .el-carousel__button {
  background-color: rgba(163, 163, 163, 0.8);
}

#details .main .content {
  float: left;
  margin-left: 25px;
  width: 640px;
}

#details .main .content .name {
  height: 30px;
  line-height: 30px;
  font-size: 24px;
  font-weight: normal;
  color: #212121;
}

#details .main .content .intro {
  color: #b0b0b0;
  padding-top: 10px;
}

#details .main .content .store {
  color: #ff6700;
  padding-top: 10px;
}

#details .main .content .price {
  display: block;
  font-size: 18px;
  color: #ff6700;
  border-bottom: 1px solid #e0e0e0;
  padding: 25px 0 25px;
}

#details .main .content .price .del {
  font-size: 14px;
  margin-left: 10px;
  color: #b0b0b0;
  text-decoration: line-through;
}

#details .main .content .pro-list {
  background: #f9f9fa;
  padding: 30px 60px;
  margin: 50px 0 50px;
}

#details .main .content .pro-list span {
  line-height: 30px;
  color: #616161;
}

#details .main .content .pro-list .pro-price {
  float: right;
}

#details .main .content .pro-list .pro-price .pro-del {
  margin-left: 10px;
  text-decoration: line-through;
}

#details .main .content .pro-list .price-sum {
  color: #ff6700;
  font-size: 24px;
  padding-top: 20px;
}

#details .main .content .button {
  height: 55px;
  margin: 10px 0 20px 0;
}

#details .main .content .button .el-button {
  float: left;
  height: 55px;
  font-size: 16px;
  color: #fff;
  border: none;
  text-align: center;
}

#details .main .content .button .shop-cart {
  width: 340px;
  background-color: #ff6700;
}

#details .main .content .button .shop-cart:hover {
  background-color: #f25807;
}

#details .main .content .button .like {
  width: 260px;
  margin-left: 40px;
  background-color: #b0b0b0;
}

#details .main .content .button .like:hover {
  background-color: #757575;
}

#details .main .content .pro-policy li {
  float: left;
  margin-right: 20px;
  color: #b0b0b0;
}

/* 主要内容CSS END */
</style>